<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\models\user\User;
use App\other\Notification\SendMail;
use Auth;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Lang;
use Validator;

class LoginController extends Controller{

    use ThrottlesLogins;

    public function __construct(){
    }

    public function loginPage(){
        if (Auth::check()){
            return redirect('/');
        }
        return view('auth.login');
    }

    public function login(Request $request){
        if (Auth::check()){
            return redirect('/');
        }
        $v = Validator::make($request->all(), [
            'email'     => 'required|email|exists:users,email',
            'password'  => 'required|min:8'
        ]);
        if ($v->fails()){
            return redirect('/login')
                ->withInput($request->all())
                ->withErrors($v->getMessageBag()->getMessages());
        }
        $user = User::where('email', $request->get('email'))->first();
        if ($user->verified == 0){
            SendMail::sendRegisterEmail($user);
            return redirect('/login')->with(['_error' => '邮箱未激活,已发送激活邮件']);
        }
        if ($user->is_ban == 1 && $user->ban_time > time()){
            return redirect('/login')->with(['_error' => '你被封禁至:'.date('Y/m/d H:i:s', $user->ban_time)]);
        }elseif ($user->is_ban == -1){
            return redirect('/login')->with(['_error' => '你已经被永久封禁']);
        }else{
            $user->is_ban = 0;
            $user->save();
        }
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        if (Auth::attempt(['email' => $request->get('email'), 'password' => $request->get('password')], false)) {
            return redirect('/');
        }
        $this->incrementLoginAttempts($request);

        return redirect('/login')->with(['_error' => Lang::get('auth.failed')])->withInput($request->all());
    }

    public function logout(Request $request){
        Auth::logout();
        return redirect('/');
    }

    protected function guard(){
        return Auth::guard();
    }

    public function username(){
        return 'email';
    }
}
